// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import App from "./App";
import router from "./router";
import url from "./config/url";

//引入请求
import Api from "./api/";
import axios from "axios";
// axios.defaults.baseURL = url.apiUrl;
Vue.prototype.$Api = Api;
import store from "./store";

//vant
import Vant from "vant";
import "vant/lib/index.css";
Vue.use(Vant);

import YDUI from "vue-ydui";
import "vue-ydui/dist/ydui.rem.css";
Vue.use(YDUI);

import Function from "./util/";
Vue.prototype.$Func = Function;
import WechatAuth from "vue-wechat-auth";
Vue.use(require("vue-wechat-title"));


// window.localStorage.clear()

//首先获取设备的社区code
let state = Function.getUrlKey("state");
if (state == null) {
  state = "state";
}
Vue.use(WechatAuth, {
  router, // 路由实例对象
  appid: "wxdfa887f71a5f755e", // 您的微信appid
  responseType: "code", // 返回类型，请填写code
  scope: "snsapi_userinfo", // 应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且，即使在未关注的情况下，只要用户授权，也能获取其信息）
  getCodeCallback(code, next) {
    // 用户同意授权后回调方法
    // code：用户同意授权后，获得code值
    // code说明： code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
    // next： 无论access_token是否获取成功,一定要调用该方法
    // next说明：next方法接收两个参数
    // 参数1为通过code值请求后端获取到的access_token值，如果获取失败请填入空字符串''
    // 参数2(非必填，默认获取access_token切换到当前路由对象)，指定切换对象 next('/') 或者 next({ path: '/' })
    if (code && code != "undefined") {
      axios
        .get("http://jxdadmin.hisway365.com/api/user/weixinshouquan", {
          params: {
            code,
            state: state
          }
        })
        .then(response => {
          let data = response.data;
          if (data.code == 200) {
            let result = data.data;
            if (result.accessToken) {
                    if (result.userList.length !== 0) {
                       window.localStorage.setItem("usertoken", result.userList[0].token);
                       window.localStorage.setItem("userType", result.userList[0].userType);
                    }
                window.localStorage.setItem("openId", result.openId);
                next(result.accessToken, { path: "/indexx" });
            } else {
              next(); // 获取access_token失败
            }
          }
        })
        .catch(() => {
          next(); // ajax出现错误
        });
    }
  }
});

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  store,
  components: { App },
  template: "<App/>"
});
